<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发布人" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入发布人名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入任务标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="dict in dict.type.task_statu"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreatedTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          :disabled="multiple"
          size="mini"
          @click="handleDetermine"
          v-hasPermi="['hurtless:minestacks:determine']"
        >确认
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hurtless:minestacks:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="minestacksList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="发布人" align="center" prop="nickName"/>
      <el-table-column label="电话号码" align="center" prop="phonenumber" width="110"/>
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <span> {{ scope.row.sex === 0 ? '男' : scope.row.sex === 1 ? '女' : '未知' }} </span>
        </template>
      </el-table-column>
      <el-table-column label="部门" align="center" prop="deptName"/>
      <el-table-column label="岗位" align="center" prop="postName"/>
      <el-table-column label="任务标题" align="center" prop="title"/>
      <el-table-column label="任务描述" align="center" prop="description"/>
      <el-table-column label="任务状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_statu" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="downloadFileToMinio(scope.row.fileName,scope.row.originalName)"
          >下载文件
          </el-button>
          <el-button
            v-show="scope.row.status === 0"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleDetermine(scope.row)"
            v-hasPermi="['hurtless:minestacks:determine']"
          >确认
          </el-button>
          <el-button
            v-show="scope.row.status !== 0"
            size="mini"
            type="text"
            icon="el-icon-position"
            @click="handleSubmit(scope.row)"
            v-hasPermi="['hurtless:minestacks:submit']"
          >提交
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="文件更新" :visible.sync="diaologVisible" width="500px">
      <el-upload
        class="upload-demo"
        action="http://127.0.0.1:8080/file/upload"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :on-success="handSuccess"
        multiple
        :limit="1"
        :on-exceed="handleExceed"
        :file-list="fileList">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传pdf文件，且不超过10MB</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cance">取 消</el-button>
    <el-button type="primary" @click="handle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMinestacks,
  submitMinestacks,
  determineMinestacks, updataFileId,
} from "@/api/hurtless/minestacks"
import {deleteFileToMiono, downloadFileToMinio} from "@/utils/fileutils/fileUtils";

export default {
  name: "Minestacks",
  dicts: ['task_statu'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数据的状态
      status: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 我的任务表格数据
      minestacksList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 任务描述时间范围
      daterangeCreatedTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nickName: null,
        title: null,
        status: null,
        createdTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          {required: true, message: "任务标题不能为空", trigger: "blur"}
        ],
        description: [
          {required: true, message: "任务描述不能为空", trigger: "blur"}
        ],
      },
      diaologVisible: false,
      fileList: [],
      // 提交的id
      id: undefined,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    downloadFileToMinio,
    /** 查询我的任务列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeCreatedTime && '' != this.daterangeCreatedTime) {
        this.queryParams.beginCreatedTime = this.daterangeCreatedTime[0]
        this.queryParams.endCreatedTime = this.daterangeCreatedTime[1]
      }
      listMinestacks(this.queryParams).then(response => {
        this.minestacksList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        description: null,
        publisherId: null,
        recipientId: null,
        accomplishTime: null,
        status: null,
        createdTime: null,
        updatedTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreatedTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.status = selection.map(item => item.status)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 确认任务操作 */
    handleDetermine(row) {
      const ids = row.id || this.ids
      let b = true
      if (Array.isArray(ids)) {
        this.status.forEach(item => {
          if (item !== 0) {
            this.$modal.msgError('你只可以确认代办的')
            b = false
            return false
          }
        })
      } else {
        if (row.status !== 0) {
          this.$modal.msgError('你只可以确认代办的')
          b = false
          return false
        }
      }
      if (b) {
        return determineMinestacks(ids).then(() => {
          this.getList()
          this.$modal.msgSuccess("成功")
        })
      }
    },
    /** 提交任务按钮操作 */
    handleSubmit(row) {
      this.id = row.id
      // 回显文件
      this.fileList = []
      if (row.fileId !== null) {
        this.fileList.push({name: row.originalName, url: row.url, fileName: row.fileName, fileId: row.fileId})
      }
      this.diaologVisible = true
    },
    /** 取消按钮*/
    cance() {
      this.fileList = []
      this.diaologVisible = false
    },
    /**确认提交任务*/
    handle() {
      submitMinestacks(this.id, this.fileList[0].fileId).then(() => {
        this.$message.success("提交成功")
        this.fileList = []
        this.diaologVisible = false
        this.resetQuery()
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hurtless/minestacks/export', {
        ...this.queryParams
      }, `minestacks_${new Date().getTime()}.xlsx`)
    },
    /** 移除文件前触发*/
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    /** 文件上传超过就会触发*/
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    /** 真正的移除文件时触发*/
    handleRemove(file, fileList) {
      // 删除远程的文件和数据库中的文件
      deleteFileToMiono(file.fileName)
      // 修改关联的文件id 的文件为null
      updataFileId(file.fileId)
      this.fileList = []
    },
    handSuccess(response, file, fileList) {
      this.fileList = []
      this.fileList.push({
        name: response.originalName,
        url: response.url,
        fileId: response.id,
        fileName: response.storedName
      })
    }
  }
}
</script>
